package db

import (
	"fmt"
	"log"
	"os"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB = nil

func dsn() string {
	user := os.Getenv("MYSQL_USER")
	password := os.Getenv("MYSQL_PASSWORD")
	ip := os.Getenv("MYSQL_IP")
	port := os.Getenv("MYSQL_PORT")
	dbname := os.Getenv("MYSQL_DBNAME")
	if user == "" || password == "" || ip == "" || port == "" || dbname == "" {
		log.Fatal("ERROR: not enough db env")
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		user,
		password,
		ip,
		port,
		dbname)
	if dsn == "" {
		log.Fatal("ERROR: db dsn parse error")
	}
	return dsn
}

func Init() {
	if DB != nil {
		return
	}
	dsn := dsn()
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("ERROR: Mysql link error")
	}
}

func GetDB() *gorm.DB {
	Init()
	return DB
}
